﻿namespace HZY.Framework.Repository.EntityFramework.Interceptor;

/// <summary>
/// pgsql 中用于区分大小写问题，注册后 like 语句不区分大小写
/// </summary>
public class PgSqlLikeDbCommandInterceptor : DbCommandInterceptor
{
    public override InterceptionResult<DbDataReader> ReaderExecuting(DbCommand command, CommandEventData eventData,
        InterceptionResult<DbDataReader> result)
    {
        command.CommandText = ReplacePgSqlLike(command.CommandText);
        return base.ReaderExecuting(command, eventData, result);
    }

    public override async ValueTask<InterceptionResult<DbDataReader>> ReaderExecutingAsync(DbCommand command,
        CommandEventData eventData, InterceptionResult<DbDataReader> result,
        CancellationToken cancellationToken = default)
    {
        command.CommandText = ReplacePgSqlLike(command.CommandText);
        return await base.ReaderExecutingAsync(command, eventData, result, cancellationToken);
    }

    public override InterceptionResult<object> ScalarExecuting(DbCommand command, CommandEventData eventData,
        InterceptionResult<object> result)
    {
        command.CommandText = ReplacePgSqlLike(command.CommandText);
        return base.ScalarExecuting(command, eventData, result);
    }

    public override async ValueTask<InterceptionResult<object>> ScalarExecutingAsync(DbCommand command,
        CommandEventData eventData, InterceptionResult<object> result, CancellationToken cancellationToken = default)
    {
        command.CommandText = ReplacePgSqlLike(command.CommandText);
        return await base.ScalarExecutingAsync(command, eventData, result, cancellationToken);
    }

    private static string ReplacePgSqlLike(string sql)
    {
        return sql.Replace(" LIKE @_", " ILIKE @_");
    }
}